#pragma once
#include"LogMessage.hpp"
#include<mysql/mysql.h>
#include<string>

class Mysql_API{
public:
    static MYSQL* mysql_create(const std::string& host, const std::string& user, 
    const std::string& passwd, const std::string& db, const unsigned int port)
    {
        //1.创建并初始化MySQL句柄
        MYSQL* mysql = new MYSQL;
        mysql_init(mysql);

        //2.连接MySQL服务器
        if (mysql_real_connect(mysql, host.c_str(), user.c_str(), passwd.c_str(),
        db.c_str(), port, NULL, 0) == nullptr)
        {
            log_message(ERROR, "数据库连接失败");
            mysql_destory(mysql);
        }

        //3.设置字符集为utf8
        if (mysql_set_character_set(mysql, "utf8") != 0)
        {
            log_message(ERROR, "数据库字符集设置失败");
            mysql_destory(mysql);
        }

        return mysql;
    }

    static bool mysql_exec(MYSQL* mysql, const std::string& sql_commend)
    {
        if (mysql_query(mysql, sql_commend.c_str()) != 0)
        {
            std::string error_message = "执行失败->";
            error_message += sql_commend;
            log_message(ERROR, "%s", error_message.c_str());
            mysql_destory(mysql);
            return false;
        }
        return true;
    }

    static void mysql_destory(MYSQL* mysql)
    {
        if (mysql != nullptr)
        {
            mysql_close(mysql);
            log_message(WARING, "数据库已关闭");
        }
    }
};